<?php
/**
* 
*/
class SelfsendAction extends Action
{	
	public function index(){
		@header('Content-Type:text/html;charset=UTF-8');
		$map['status'] = '1';
		$array = M('lendlog')->where($map)->select();
		//dump($array);
		if($array){
		foreach ($array as $key => $value) {
			$mes = M('message')->where(array('lid'=>$value['id']))->find();
			if(time()-$mes['time']>=24*60*60||empty($mes)){
				if(time()-$value['lendtime']>=6*24*60*60){
					$time = date('Y-m-d',$value['lendtime']+6*24*60*60);
					$bookname = M('book')->where(array('id'=>$value['bid']))->getField('book_name');
					$openid =M('user')->where(array('id'=>$value['wid']))->getField('openid');
					$this->send($openid,$bookname,$time);
					$meslog = M('message')->where(array('lid'=>$value['id']))->find();
					if($meslog){
						$data['lid'] = $value['id'];
						$data['time'] = time();
						$data['content'] = '尊敬的用户： 您还有书'.$bookname.'未还，逾期时间'.$time.'。请尽快还书。';
						M('message')->where(array('lid'=>$value['id']))->save($data);
					}else{
						$data['lid'] = $value['id'];
						$data['time'] = time();
						$data['content'] = '尊敬的用户： 您还有书'.$bookname.'未还，逾期时间'.$time.'。请尽快还书。';
						M('message')->add($data);
					}
				}
			}
		}
	  }
	  dump('消息已经全部发送');
	}
	public function send($openid,$bookname,$time){
		
		$json_token=$this->http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9d8f3d6a105a7b28&secret=9638441d52c7b712637ead74d0922401");
		$access_token=json_decode($json_token,true);
		//获得access_token
		$this->access_token=$access_token[access_token];
		//dump($this->access_token);die;
	//echo $this->access_token;exit;
	//模板消息
	$template=array(
	        'touser'=>$openid,
	        'template_id'=>"kEojA44QRZBCCFmO1ErVwljO_8hn3f8YcDhQrMHUSTk",
	        'url'=>"",
	        'topcolor'=>"#7B68EE",
	        'data'=>array(
	                'bookname'=>array('value'=>urlencode($mcsinfo['mcs_name'].$bookname),'color'=>"#FF0000"),
	                'time'=>array('value'=>$time,'color'=>'#FF0000'),
	                 )
	            );
	$json_template=json_encode($template);
	//echo $json_template;
	//echo $this->access_token;
	$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
	$res=$this->http_request($url,urldecode($json_template));
	if ($res[errcode]==0) return 1;
		}
//post方法
function http_request($url,$data=array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}}

?>